<template>
  <div class="frequency-node">
    <el-form label-position="top" :rules="rules" label-width="80px" :model="formData" ref='nodeForm'>
      <el-form-item label="时间周期" prop="executeStrategy">
        <el-select v-model="formData.executeStrategy" @change="changeStrategy" placeholder="请选择">
          <el-option v-for="item in strategyList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 自定义时间周期 -->
      <el-form-item v-if="formData.executeStrategy === 'customize'" class="every-form">
        <div slot='label' class="every-form-label">选择周期</div>
        <el-form-item prop="executeStrategyType">
          <el-select v-model="formData.executeStrategyType" @change="changeStrategyType" placeholder="请选择">
            <el-option label="固定周期" :value="1"></el-option>
            <el-option label="自定义时段" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- 自定义时间周期 固定周期 -->
        <div v-if="formData.executeStrategyType === 1" class="time-item fixed-time">
          <el-form-item prop="limitTime">
            <el-input-number v-model="formData.limitTime" :min="1" :max='200' placeholder="请输入" class="input-number time-limit-count" :controls='false' :precision='0'></el-input-number>
          </el-form-item>
          <el-form-item prop="limitUnit">
            <el-select v-model="formData.limitUnit" placeholder="请选择" class="choose-time-unit">
              <el-option label="秒" value="second"></el-option>
              <el-option label="分钟" value="min"></el-option>
              <el-option label="小时" value="hour"></el-option>
            </el-select>
          </el-form-item>
          <span class="time-item-unit">内最多执行 &nbsp; </span>
          <el-form-item prop="executeStrategyTimes">
            <el-input-number v-model="formData.executeStrategyTimes" :min="1" :max='99' placeholder="请输入" class="input-number choose-time-unit" :controls='false' :precision='0'></el-input-number>
          </el-form-item>
          <span class="time-item-unit">次</span>
        </div>
        <!-- 自定义时间周期 自定义时段 -->
        <div v-else v-for="(item, index) in formData.timeList" :key="item.key" class="time-item">
          <el-form-item :prop="`timeList[${index}].timeRange`" :rules="rules.timeRange">
            <el-time-picker v-model="item.timeRange" @change="changeTimeRange" value-format="HH:mm:00" format="HH:mm" is-range :class='`custom-picker ${errIndex.includes(index)}`' prefix-icon='el-icon-time' popper-class='frequency-custom-picker-popper' :clearable='false'></el-time-picker>
          </el-form-item>
          <el-form-item :prop="`timeList[${index}].count`" :rules="rules.count">
            <el-input-number v-model="item.count" :min="1" :max='99' placeholder="请输入" class="input-number time-item-count" :controls='false' :precision='0'></el-input-number>
          </el-form-item>
          <span class="time-item-unit">次</span>
          <div class="tool-bar">
            <svg-icon icon-class="删除" className="signal-open" @click="deleteTimeRange(index)"/>
          </div>
        </div>
        <el-button v-if="formData.executeStrategyType === 2 && formData.timeList.length < 10" type="text" class="add-scene" @click="addTimeItem">
          <i class="el-icon-circle-plus"></i>
          添加时间段
        </el-button>
      </el-form-item>
      <!-- 上电、每天、每三天、每周 -->
      <el-form-item v-else label="限制次数(次)" prop="executeStrategyTimes">
        <el-input-number v-model="formData.executeStrategyTimes" :min="1" :max='99' placeholder="请输入" class="input-number" :controls='false' :precision='0'></el-input-number>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { deepClone } from '@/utils/helper/jsUtil'
import RuleNodeBaseClass from '@/components/ruleNode/RuleNodeBaseClass'
import { validateTime } from './frequencyNode.util'
import { mapState } from 'vuex'

export default {
  name: 'AdvancedLibFrequencyNode',
  mixins: [RuleNodeBaseClass],
  props: {
  },
  data() {
    // const timeValidate = (rule, value, callback) => {
    //   if (value.length === 2 && value[0] === value[1]) {
    //     callback(new Error(' '))
    //   }
    //   callback()
    // }
    return {
      asdf: '',
      formData: {
        executeStrategy: '',
        limitTime: '',
        limitUnit: 'min',
        executeStrategyType: 1,
        timeList: [],
        executeStrategyTimes: ''
      },
      rules: {
        executeStrategy: [{ required: true, message: '时间周期不能为空', trigger: 'change' }],
        limitTime: [{ required: true, message: '时间周期不能为空', trigger: 'blur' }],
        limitUnit: [{ required: true, message: '时间单位不能为空', trigger: 'change' }],
        executeStrategyTimes: [{ required: true, message: '限制次数不能为空', trigger: 'blur' }],
        executeStrategyType: [{ required: true, message: '限制方式不能为空', trigger: 'change' }],
        timeRange: [{ required: true, type: 'array', message: ' ', trigger: 'change' }],
        count: [{ required: true, message: ' ', trigger: 'blur' }]
      },
      errIndex: [] // 时间冲突项index
    }
  },
  mounted() {
    this.initValue()
  },
  methods: {
    initValue() {
      const initFormData = this.initialForm ? deepClone(this.initialForm) : {}
      // 秒数格式化
      initFormData.timeList?.forEach(time => {
        const str = time.timeRange[1].split(':')
        str[2] = '00'
        time.timeRange[1] = str.join(':')
      })
      Object.assign(this.formData, initFormData)
      this.formData.executeStrategyTimes = this.formData.executeStrategyTimes || undefined
    },
    changeStrategy(val) {
      if (val === 'customize') {
        this.formData.executeStrategyType = 1
        this.changeStrategyType(1)
      } else {
        this.formData.executeStrategyTimes = undefined
      }
      this.$refs.nodeForm.clearValidate()
    },
    changeStrategyType(type) {
      if (type === 1) {
        this.formData.timeList = []
        this.formData.limitTime = undefined
        this.formData.limitUnit = 'min'
      } else {
        this.formData.executeStrategyTimes = undefined
        this.addTimeItem()
      }
    },
    addTimeItem() {
      const now = new Date()
      this.formData.timeList.push({
        key: now.getTime() + '',
        timeRange: [`${now.getHours()}:${now.getMinutes()}:00`, '23:59:00'],
        count: undefined
      })
    },
    changeTimeRange(val) {
      this.validateTimeList()
    },
    validateTimeList() {
      const res = validateTime(this.formData.timeList)
      this.errIndex = [...new Set(res.list)]
    },
    deleteTimeRange(index) {
      if (this.formData.timeList.length > 1) {
        this.formData.timeList.splice(index, 1)
        this.validateTimeList()
      }
    },
    getFormData() {
      // 秒数格式化
      const data = deepClone(this.formData)
      data.timeList?.forEach(time => {
        const str = time.timeRange[1].split(':')
        str[2] = '59'
        time.timeRange[1] = str.join(':')
      })
      return data
    },
    validateForm() {
      let isValid
      this.$refs.nodeForm.validate(valid => { isValid = valid })
      if (this.formData.executeStrategyType === 2) {
        const res = validateTime(this.formData.timeList)
        if (!res.result) {
          this.errIndex = [...new Set(res.list)]
          this.$message.error('时间区间冲突！请修改！')
        }
        isValid = (isValid && res.result)
      }
      return isValid
    }
  },
  computed: {
    ...mapState({
      productType: state => state.product.type
    }),
    strategyList() {
      const strategyList = [
        { value: 'everyDay', label: '每天' },
        { value: 'everyThreeDay', label: '每三天' },
        { value: 'everyWeek', label: '每周' },
        { value: 'customize', label: '自定义周期' }
      ]
      const firstOptions = {
        vehicle: { value: 'currentStart', label: '本次上电周期' },
        cloud: { value: 'currentShutDown', label: '本次下电周期' }
      }
      strategyList.unshift(firstOptions[this.productType])
      return strategyList
    }
  }
}
</script>
<style lang="scss">
.frequency-node {
  .input-number{
    width: 100%;
    .el-input__inner{
      text-align: left;
    }
  }
  .every-form{
    .every-form-label::before{
      content: "*";
      color: #E15863;
      margin-right: 4px;
    }
    .el-form-item{
      margin-bottom: 8px;
    }
    .time-item{
      display: flex;
      .custom-picker{
        .el-range__icon{
          line-height: 30px;
          position: absolute;
          right: 0;
        }
        .el-range-input{
          text-align: left;
        }
        &.true{
          border-color: #E15863
        }
      }
      .time-item-count{
        margin-left: 8px;
        width: 144px;
      }
      .time-item-unit{
        margin-left: 8px;
        color: #C0C4CC;
      }
    }
    .fixed-time{
      .choose-time-unit{
        width: 100px;
      }
      & .el-form-item:nth-child(1){
        flex: 1;
      }
    }
    .tool-bar {
      margin-left: 12px;
      font-size: 16px;
      cursor: pointer;
    }
    .add-scene {
      font-size: 14px;
    }
  }
}
.frequency-custom-picker-popper{
  .el-time-panel__content::before, .el-time-panel__content::after{
    margin-top: -8px;
  }
}
</style>
